<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Symfony\Component\HttpFoundation\Response;

class CheckToken
{
    public array $routeWhiteList = [
        'api/token'
    ];

    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     * @return Response
     */
    public function handle(Request $request, Closure $next): Response
    {
        // 1. 路由白名单
        if ($this->checkWhiteList($request)) {
            return $next($request);
        }

        // 2. 从 header 头里获取 token，如果没有 token，就抛出异常，并停止访问
        $token = $request->header('token');
        if (is_null($token)) {
            return result(401, 'token is missing');
        }

        // 3. 验证 header 头里 token 的真实性是否失效，如果失效，同样抛出异常，并停止访问
        $valid = $this->verifyToken($token);
        if (!$valid) {
            return result(401, 'token is invalid');
        }

        return $next($request);
    }

    private function verifyToken($token): bool
    {
        return !empty(Cache::get($token));
    }

    public function checkWhiteList($request): bool
    {
        $route = $request->route()->uri();
        return in_array($route, $this->routeWhiteList);
    }
}
